import { defineComponent, reactive, ref, Teleport, toRaw, unref } from 'vue';
import './index.less';
import type { CardListQuery } from '/@/api/verse/model/cardModel';
import { CardList } from '/@/api/verse/model/cardModel';
import Title from '/@/views/verse/components/Title';
import BaseSearch from '/@/views/verse/components/CardSearch/BaseSearch';
import SeriesSearch from '/@/views/verse/components/CardSearch/SeriesSearch';
import { CardListApi } from '/@/api/verse/card';
import { aTabClick, awaitWrap, filterNullAttributes, judgeSystem } from '/@/utils';
import { Button, Empty, Field, List } from 'vant';
import { Icon } from '/@/components/Icon';
import { useGo } from '/@/hooks/web/usePage';
import { appShareUsing } from '/@/utils/appInteractive';
import setting from '/@/settings/projectSetting';
import { WeChatUrlApi } from '/@/api/common';
import { GameIdEnum } from '/@/api/model/commonModel';

export default defineComponent({
  name: 'VerseCardPage',
  setup() {
    // 设置分享参数
    appShareUsing({
      title: '',
      content: '',
      image: '',
      url: window.location.href,
    });

    const go = useGo();

    const queryState = reactive<CardListQuery>({
      page: 1,
      page_size: 30,
      message: '',
      rarity: [],
      card_career: [],
      card_category: [],
      mana: [],
      series_id: [],
    });
    const searchFieldSlot = {
      button: () => {
        return (
          <Button
            type={'primary'}
            size={'small'}
            onClick={() => {
              getList(true);
            }}
          >
            搜索
          </Button>
        );
      },
    };

    // 数据获取
    const listLoading = ref(false); // 是否处于加载状态 默认不处于，流会去加载数据
    const listFinished = ref(false); // 是否全部数据加载完成
    const listEmpty = ref(false);
    const listData = reactive<CardList>({
      total: 0,
      rows: [],
    });

    /**
     *
     * @param isRefresh 是否重新加载列表
     */
    const getList = async (isRefresh: boolean) => {
      if (isRefresh) {
        queryState.page = 1;
        listLoading.value = true;
        listData.rows = [];
      }
      const params: CardListQuery = filterNullAttributes(queryState, []);
      const [error, data] = await awaitWrap(CardListApi(toRaw(params)));
      if (error) {
        return;
      }
      const result = data as CardList;
      if (queryState.page === 1) {
        listData.total = result.total;
        listFinished.value = false;
        !result.total ? (listEmpty.value = true) : (listEmpty.value = false);
      }
      for (const item of result.rows) {
        listData.rows.push(item);
      }
      queryState.page += 1;
      listLoading.value = false;
      if (listData.rows.length >= listData.total) {
        listFinished.value = true;
      }
    };
    const GetCardItem = ({ cardList }: { cardList: CardList }) => {
      const listArr: VueNode[] = [];
      cardList.rows.map((item) => {
        listArr.push(
          <li
            class={'card-item'}
            onClick={() => {
              go(`/versecard/${item.card_id}`);
            }}
          >
            <div class='image'>
              <img src={item.img} alt='' />
            </div>
            <div class={'name-box'}>
              <div class={'name-content van-ellipsis text-xs text-white px-md'}>
                [{item.is_foil ? '闪' : '平'}]{item.name}
              </div>
            </div>
          </li>
        );
      });
      return <ul class='card-list flex flex-wrap'>{listArr}</ul>;
    };

    // 筛选Popup
    const searchState = ref(false);
    const seriesPopupState = ref(false);
    // 打开其他条件筛选
    const filterClick = () => {
      searchState.value = true;
    };
    // 打开系列筛选
    const seriesPopupClick = () => {
      seriesPopupState.value = true;
    };

    // 适配安卓键盘
    const bottomSearchClass = ref('');
    const fieldFocusClick = () => {
      console.log(judgeSystem());
      if (judgeSystem() === 'android') {
        bottomSearchClass.value = 'android';
        return false;
      }
      bottomSearchClass.value = '';
    };
    const fieldBlurClick = () => {
      bottomSearchClass.value = '';
    };

    // 跳转到小程序
    const weChatClick = async () => {
      const [error, data] = await awaitWrap(WeChatUrlApi({ game_id: GameIdEnum.VERSE }));
      if (error || !data) {
        aTabClick(setting.wechatAppHomeUrl, '_blank');
        return;
      }
      aTabClick(data, '_blank');
    };

    return () => (
      <div class='verse-card-container'>
        <Title title='影之诗Evolve' />
        <div class={'card-list-container'}>
          {unref(listEmpty) ? (
            <Empty>未找到相关卡牌</Empty>
          ) : (
            <List
              v-model={[listLoading.value, 'loading']}
              finished={unref(listFinished)}
              finishedText={'没有更多卡牌'}
              onLoad={getList}
            >
              <GetCardItem cardList={listData} />
            </List>
          )}
        </div>
        <div class={`bottom-area flex ${unref(bottomSearchClass)}`}>
          <div class={'bottom-search flex items-center'}>
            <div class={'input-box'}>
              <Field
                v-model={[queryState.message]}
                placeholder='卡牌名称或规则'
                leftIcon={'search'}
                v-slots={searchFieldSlot}
                clearable
                onFocus={fieldFocusClick}
                onBlur={fieldBlurClick}
              />
            </div>
            <div class='svg-button mall text-center' onClick={weChatClick}>
              <Icon icon={'single-mall|svg'} size={30} />
              <span class={'block text-sm'}>淘卡</span>
            </div>
            <div class='svg-button filter text-center' onClick={filterClick}>
              <Icon icon={'single-filter|svg'} size={30} />
              <span class={'block text-sm'}>筛选</span>
            </div>
          </div>
        </div>

        <Teleport to={'body'}>
          <BaseSearch
            v-model={[searchState.value, 'show']}
            queryState={queryState}
            onPageRefresh={() => {
              getList(true);
            }}
            onOpenSeriesPopup={seriesPopupClick}
          />
          <SeriesSearch
            v-model={[seriesPopupState.value, 'show']}
            queryState={queryState}
            onPageRefresh={() => {
              getList(true);
            }}
          />
        </Teleport>
      </div>
    );
  },
});
